# -*- coding: utf-8 -*-
# --------------------------------------
# @Time    : 2025/7/16 18:36
# @File    : sqlhelper.py
# @Project : P0716sayhello
# @Author  : CHH
# @Desc    : Windows   文件描述
# @Copyright : © 2025 HORDOR . All rights reserved.
# @Version : 1.0.0
# --------------------------------------
import pymysql
from dbutils import pooled_db
from config import settings
from pymysql import cursors


class SqlHelper(object):
    def __init__(self):
        self.pool = pooled_db.PooledDB(
            creator=pymysql,
            mincached=2,
            maxcached=3,
            maxconnections=10,
            host=settings.HOST,
            port=settings.PORT,
            user=settings.USER,
            passwd=settings.PASSWD,
            db=settings.DB,
            blocking=True,
            setsession=[],
            ping=0,
            charset="utf8mb4"
        )

    def open(self):
        conn = self.pool.connection()
        cursor = conn.cursor(cursors.DictCursor)
        return conn, cursor

    def close(self, conn, cursor):
        conn.close()
        cursor.close()

    def fetch_one(self, sql, params):
        conn, cursor = self.open()
        cursor.execute(sql, params)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def fetch_all(self, sql, params):
        conn, cursor = self.open()
        cursor.execute(sql, params)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def insert_one(self, sql, params):
        conn, cursor = self.open()
        cursor.execute(sql, params)
        conn.commit()
        self.close(conn, cursor)
        # return cursor.lastrowid


db = SqlHelper()
